package com.xg.serviceOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xg.common.constant.CommonStatusEnum;
import com.xg.common.constant.OrderConstant;
import com.xg.common.constant.RedisKeyConstant;
import com.xg.common.result.ApiResult;
import com.xg.serviceOrder.entity.UsedCarOrder;
import com.xg.serviceOrder.entity.UsedCarOrderItem;
import com.xg.serviceOrder.mapper.UsedCarOrderItemMapper;
import com.xg.serviceOrder.mapper.UsedCarOrderMapper;
import com.xg.serviceOrder.remote.ServiceCarFeignClient;
import com.xg.serviceOrder.service.UsedCarOrderItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.Lock;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author li
 * @since 2023-04-04
 */
@Service
public class UsedCarOrderItemServiceImpl extends ServiceImpl<UsedCarOrderItemMapper, UsedCarOrderItem> implements UsedCarOrderItemService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UsedCarOrderMapper orderMapper;

    @Autowired
    private UsedCarOrderItemMapper orderItemMapper;

    @Autowired
    private ServiceCarFeignClient carFeignClient;

    /**
     * 创建订单--->支付
     *
     * @param orderId
     * @param orderNumber
     * @return
     */
    @Transactional
    @Override
    public ApiResult add(Long orderId, String orderNumber) {
        QueryWrapper<UsedCarOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber);
        UsedCarOrderItem existsOrderItem = orderItemMapper.selectOne(queryWrapper);
        if (null != existsOrderItem){
            return ApiResult.success(existsOrderItem);
        }
        // 验证防重提交
        UsedCarOrder usedCarOrder = orderMapper.selectById(orderId);
        Lock lock = new Lock();
        try {
            lock.lock();
            String orderKey = RedisKeyConstant.ORDER_TOKEN_PREFIX+usedCarOrder.getOrderId();
            String orderToken = stringRedisTemplate.opsForValue().get(orderKey);
            if (null != orderToken && usedCarOrder.getOrderNumber().equals(orderToken)){
                // 第一次提交
                stringRedisTemplate.delete(orderKey);
            }else {
                // 多次提交
                return ApiResult.error(CommonStatusEnum. ORDER_CREATE_EXCEPTION.getCode(),CommonStatusEnum. ORDER_CREATE_EXCEPTION.getMsg());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }

        // 插入订单明细
        UsedCarOrderItem usedCarOrderItem = new UsedCarOrderItem();
        BeanUtils.copyProperties(usedCarOrder,usedCarOrderItem);
        usedCarOrderItem.setUsedCarSellPrice(usedCarOrderItem.getUsedCarSellPrice()*10000);
        usedCarOrderItem.setSubmissionTime(LocalDateTime.now());
        usedCarOrderItem.setOrderStatus(OrderConstant.OrderStatusEnum.FOR_THE_PAYMENT.getCode());
        orderItemMapper.insert(usedCarOrderItem);
        return ApiResult.success(usedCarOrderItem);
    }

    @Override
    public void updateOrderAndUsedCar(Map<String, Object> map) {
        String tradeNo = (String) map.get("tradeNo");
        String alipayTradeNo = (String) map.get("alipayTradeNo");
        Double payPrice = (Double) map.get("pay_price");
        //根据订单号查询订单找到车辆id
        UsedCarOrderItem orderItem = orderItemMapper.selectByOrderNumber(tradeNo);
        //更新车辆状态
        carFeignClient.updateUsedCar(orderItem.getUsedCarId());
        //更新订单状态
        orderItem.setAlipayTradeNo(alipayTradeNo);
        orderItem.setUserPayAmount(payPrice);
        orderItemMapper.updateById(orderItem);
    }
}
